﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI.MobileControls;
using Module;
using System.Data;
using Cit.CDE.Net.Module;
using UserControl;

public partial class main_admin_ModifyKey : UserControl.CommonPage
{
    #region 变量
    /// <summary>
    /// sql语句集
    /// </summary>
    private StringBuilder sbr_sql;
    /// <summary>
    /// sql语句
    /// </summary>
    private string sql;
    /// <summary>
    /// 查询数据
    /// </summary>
    private DataTable query_tb;
    /// <summary>
    /// 旧密钥
    /// </summary>
    private string old_key;
    /// <summary>
    /// 新密钥
    /// </summary>
    private string new_key;

    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        sql = "SELECT VALUE FROM M_PARAMETER WHERE NAME = 'des'";

        query_tb = Util.loadSql(sql);

        if (query_tb.Rows.Count > 0 && Util.objectToString(query_tb.Rows[0].ItemArray[0]) != "")
        {
            //加密状态
            this.type.Text = "加密状态！";
        }
        else 
        {
            //解密状态
            this.type.Text = "解密状态！";
        }
    }
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        sql = "SELECT VALUE FROM M_PARAMETER WHERE NAME = 'des'";

        query_tb = Util.loadSql(sql);

        if (query_tb.Rows.Count > 0 && Util.objectToString(query_tb.Rows[0].ItemArray[0]) != "")
        {
            //已经加密
            base.showMessageErrAndOk("已经加密！");
        }
        else
        {

            sbr_sql = new StringBuilder();

            sbr_sql.AppendLine("SELECT");
            sbr_sql.AppendLine("A.NAME,B.CLM_NAME");
            sbr_sql.AppendLine("FROM M_TABLE_TBL A");
            sbr_sql.AppendLine("INNER JOIN M_CLM_TBL B");
            sbr_sql.AppendLine("ON A.ID = B.TABLE_P");
            sbr_sql.AppendLine("WHERE B.ENCRYPT_FLAG = 2");
            sbr_sql.AppendLine("ORDER BY A.NAME");

            query_tb = Util.loadSql(sbr_sql.ToString());

            if (query_tb.Rows.Count > 0) 
            {
                string key = Util.randomGuidCode(8);

                List<string> exeSqlList = this.getExeSqlAll(this.getTableAndColumn(query_tb), key, true);

                exeSqlList.Add("UPDATE M_PARAMETER SET VALUE = '" + key + "' WHERE NAME = 'des'");

                TransactionSql ts = new TransactionSql();

                bool result = ts.getExecuteResult(exeSqlList);

                if (result)
                {
                    //加密状态
                    this.type.Text = "加密状态！";
                    //成功
                    base.showMessageErrAndOk("加密成功！");
                }
                else 
                {
                    //失败
                    base.showMessageErrAndOk("加密失败！");
                }
            }
        }
    }
    /// <summary>
    /// 获取表名和对应的字段名
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private DataTable getTableAndColumn(DataTable dt) 
    {
        DataTable rtTable = new DataTable();
        rtTable.Columns.Add("NAME");
        rtTable.Columns.Add("COLUMN");

        string name = string.Empty;

        DataRow dr = rtTable.NewRow();

        foreach (DataRow row in query_tb.Rows)
        {
            if (Util.objectToString(row.ItemArray[0]) != name)
            {
                if (name != string.Empty) 
                {
                    rtTable.Rows.Add(dr);
                    dr = rtTable.NewRow();
                }
                name = Util.objectToString(row.ItemArray[0]);
                dr[0] = name;
                dr[1] = Util.objectToString(row.ItemArray[1]);
            }
            else 
            {
                dr[1] = dr[1] + "," + Util.objectToString(row.ItemArray[1]);
            }
        }
        rtTable.Rows.Add(dr);

        return rtTable;
    }
    /// <summary>
    /// 获得多表的执行sql
    /// </summary>
    /// <param name="dt">表名和所需字段 第一列为表名，第二列为字段名集合（用逗号分隔）</param>
    /// <param name="key">密钥</param>
    /// <param name="type">类型 true:加密 false:解密</param>
    /// <returns></returns>
    private List<string> getExeSqlAll(DataTable dt,string key,bool type) 
    {
        StringBuilder str = new StringBuilder();

        List<string> list = new List<string>();

        foreach (DataRow dr in dt.Rows) 
        {
            str.Append("SELECT ID,");
            str.Append(Util.objectToString(dr.ItemArray[1]));
            str.Append(" FROM ");
            str.Append(Util.objectToString(dr.ItemArray[0]));

            list.AddRange(getExeSql(str.ToString(), Util.objectToString(dr.ItemArray[0]), key, type));

            str = new StringBuilder();

        }
        return list;
    }
    /// <summary>
    /// 获得单表的执行sql
    /// </summary>
    /// <param name="sql">查询语句</param>
    /// <param name="tbName">表名</param>
    /// <param name="key">密钥</param>
    /// <param name="type">类型 true:加密 false:解密</param>
    /// <returns></returns>
    private List<string> getExeSql(string sql,string tbName,string key,bool type) 
    {
        List<string> list = new List<string>();

        StringBuilder rtStr = new StringBuilder();

        DataTable dt = Util.loadSql(sql);

        foreach (DataRow dr in dt.Rows) 
        {
            rtStr.AppendFormat("UPDATE {0} SET ",tbName);

            for (int i = 1; i < dt.Columns.Count; i++)
            {
                if (i == 1)
                {
                    if (Util.objectToString(dr.ItemArray[i]) == "")
                    {
                        rtStr.AppendFormat("{0} = null ", dt.Columns[i].ColumnName);
                    }
                    else
                    {
                        if (type)
                        {

                            rtStr.AppendFormat("{0} = '{1}' ", dt.Columns[i].ColumnName,
                                getEncryptData(Util.objectToString(dr.ItemArray[i]), key));
                        }
                        else
                        {
                            rtStr.AppendFormat("{0} = '{1}' ", dt.Columns[i].ColumnName,
                                getDecryptData(Util.objectToString(dr.ItemArray[i]), key));
                        }
                    }
                }
                else
                {
                    if (Util.objectToString(dr.ItemArray[i]) == "")
                    {
                        rtStr.AppendFormat(",{0} = null ", dt.Columns[i].ColumnName);
                    }
                    else
                    {
                        if (type)
                        {
                            rtStr.AppendFormat(", {0} = '{1}' ", dt.Columns[i].ColumnName,
                                getEncryptData(Util.objectToString(dr.ItemArray[i]), key));
                        }
                        else
                        {
                            rtStr.AppendFormat(", {0} = '{1}' ", dt.Columns[i].ColumnName,
                                getDecryptData(Util.objectToString(dr.ItemArray[i]), key));
                        }
                    }
                }
            }

            rtStr.AppendFormat(" WHERE ID = {0};", Util.objectToString(dr.ItemArray[0]));
            
            list.Add(rtStr.ToString());

            rtStr.Length = 0;
        }

        return list;
    }
    /// <summary>
    /// 数据解密
    /// </summary>
    /// <param name="oldData">加密数据</param>
    /// <param name="key">密钥</param>
    /// <returns></returns>
    private string getDecryptData(string oldData,string key) 
    {
        CDESecurity.UserDESKey = key;

        if (oldData.Length == 0) 
        {
            return "";
        }

        return CDESecurity.UserDESDecryptor(oldData);
    }
    /// <summary>
    /// 数据加密
    /// </summary>
    /// <param name="oldData">加密数据</param>
    /// <param name="key">密钥</param>
    /// <returns></returns>
    private string getEncryptData(string oldData, string key)
    {
        CDESecurity.UserDESKey = key;

        if (oldData.Length == 0)
        {
            return "";
        }

        return CDESecurity.UserDESEncrypt(oldData);
    }
    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDEcrypt_Click(object sender, EventArgs e)
    {
        sql = "SELECT VALUE FROM M_PARAMETER WHERE NAME = 'des'";

        query_tb = Util.loadSql(sql);

        string key = Util.objectToString(query_tb.Rows[0].ItemArray[0]);

        if (query_tb.Rows.Count == 0 || Util.objectToString(query_tb.Rows[0].ItemArray[0]) == "")
        {
            //已经解密
            base.showMessageErrAndOk("已经解密！");
        }
        else
        {

            sbr_sql = new StringBuilder();

            sbr_sql.AppendLine("SELECT");
            sbr_sql.AppendLine("A.NAME,B.CLM_NAME");
            sbr_sql.AppendLine("FROM M_TABLE_TBL A");
            sbr_sql.AppendLine("INNER JOIN M_CLM_TBL B");
            sbr_sql.AppendLine("ON A.ID = B.TABLE_P");
            sbr_sql.AppendLine("WHERE B.ENCRYPT_FLAG = 2");
            sbr_sql.AppendLine("ORDER BY A.NAME");

            query_tb = Util.loadSql(sbr_sql.ToString());

            if (query_tb.Rows.Count > 0)
            {
                
                List<string> exeSqlList = this.getExeSqlAll(this.getTableAndColumn(query_tb), key, false);

                exeSqlList.Add("UPDATE M_PARAMETER SET VALUE = '' WHERE NAME = 'des'");

                TransactionSql ts = new TransactionSql();

                bool result = ts.getExecuteResult(exeSqlList);

                if (result)
                {
                    CDESecurity.UserDESKey = null;
                    //解密状态
                    this.type.Text = "解密状态！";
                    //成功
                    base.showMessageErrAndOk("解密成功！");
                }
                else
                {
                    //失败
                    base.showMessageErrAndOk("解密失败！");
                }
            }
        }

    }
}
